<template>
  <div>
    <bread :second="'商品管理'" :third="'参数列表'"></bread>
    <!--------------------------------- 卡片 --------------------------------------->
    <el-card class="box-card" style="margin-top:15px ">
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon :closable="false"></el-alert>
      <!------------------------- 级联选择器 -------------------------------->
      <div class="block" style="margin-top:20px">
        <span class="demonstration">选择商品分类：</span>
        <el-cascader
          v-model="value"
          :options="cateCasList"
          :props="props"
          @change="handleChange"
          clearable
        ></el-cascader>
      </div>
      <!------------------------ tab栏切换组件 -------------------------------------->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <!-------------------tab 按钮1 --------------------------->
          <el-button type="primary" size="mini" :disabled="disabled" @click="addParams()">添加参数</el-button>
          <!------------------------------ manyDate表格组件 ----------------------------------->
          <el-table :data="manyDate" style="width: 100%" border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染小标签 -->
                <el-tag
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                  style="margin:5px"
                  closable
                  @close="delTag(index,scope.row)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                  style="width:120px"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column label="参数名称 " prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <!---------------- 编辑。删除按钮 插槽 ------------------------>
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="handerEdit(scope.row)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="handerDelete(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态参数" name="only">
          <!-------===================== 按钮2 ===========================================------------>
          <el-button type="primary" size="mini" :disabled="disabled" @click="addParams()">添加属性</el-button>
          <!-- -------------------------onlyDate组件------------------------------ -->
          <el-table :data="onlyDate" style="width: 100%" border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染小标签 -->
                <el-tag
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                  style="margin:5px"
                  closable
                  @close="handleClose(index,scope.row)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                  style="width:120px"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column label="参数名称 " prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <!---------------- 编辑。删除按钮 插槽 ------------------------>
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="handerEdit(scope.row)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="handerDelete(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-------------------------------- 表格编辑按钮弹窗 -------------------------------------->
    <el-dialog title="修改动态参数" :visible.sync="dialogFormVisible">
      <el-form :model="paramsForm" ref="paramsFormDialog" :rules="rulesForm">
        <el-form-item label="动态参数" prop="attr_name" label-width="120px">
          <el-input v-model="paramsForm.attr_name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams()">确 定</el-button>
      </div>
    </el-dialog>
    <!---------------------------------- 表格编辑按钮弹窗 ---------------------------------------->
    <!------------------------------ 动态属性按钮弹窗 ------------------------------------->
    <el-dialog title="添加动态参数" :visible.sync="addDialogFormVisible">
      <el-form :model="addForm" :rules="rulesForm" ref="paramsFormDialog">
        <el-form-item label="动态参数" label-width="120px" prop="attr_name">
          <el-input v-model="addForm.attr_name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParamsBtn">确 定</el-button>
      </div>
    </el-dialog>
    <!------------------------------ 动态属性按钮弹窗 ------------------------------------->
  </div>
</template>
           
<script>
import { getCategories_api, getCateList_api } from "@/api/login_api.js";
import {
  deleteCate_api,
  editCategories_api,
  addParams_api,
  putCategories_api
} from "@/api/index.js";

export default {
  data() {
    return {
      //级联选择器属性----------------------
      cateCasList: [],
      value: [],
      props: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        expandTrigger: "hover"
      },
      //tab栏属性--------------------------
      activeName: "many",
      disabled: true,
      //table表格------------------------
      manyDate: [],
      onlyDate: [],
      inputValue: "", //tag标签的btn按钮变成的input
      inputVisible: "",
      //编辑弹窗--------------------
      dialogFormVisible: false,
      paramsForm: {
        attr_name: ""
      },
      rulesForm: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" },
          { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" }
        ]
      },
      //属性添加按钮弹窗--------------------
      addDialogFormVisible: false,
      addForm: { attr_name: "" }
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    ////发送sxios请求，获取商品类表数据---------------------------
    async getCateList() {
      const { data: res } = await getCategories_api({ type: 3 });
      // console.log(res, 66666);
      this.cateCasList = res.data;
      this.tableData = res.data;
    },
    //级联选择器自带事件-------渲染table表格------------------------------
    async handleChange() {
      // console.log(this.value.length,22222222);
      //当级联选择第三层的数据时，解禁2个按钮，选择一层或二层不解禁
      //判断 value 数组的长度是否等于3
      if (this.value.length === 3) {
        this.disabled = false;
        this.paramsFunc();
        //渲染表单里的参数名称里的数据------------
        //发送请求要传入 id sel 值
        //id时第三层数据的id ，sel 时tab切换的两个 属性
        /* var id = this.value[this.value.length - 1];
        //  console.log(this.value,55555);
        var sel = this.activeName;
        const { data: res } = await getCateList_api({ id, sel });
        console.log(res, 8888888);
        //显示table 判断时 only 还是 many
        if (this.activeName == "many") {
          this.manyDate = res.data;
        } else {
          this.onlyDate = res.data;
        } */
      } else {
        this.value = [];
        this.disabled = true;
        this.manyDate = [];
        this.onlyDate = [];
      }
    },
    //封装获取表格的函数-----------------------------
    async paramsFunc() {
      //渲染表单里的参数名称里的数据------------
      //发送请求要传入 id sel 值
      //id时第三层数据的id ，sel 时tab切换的两个 属性
      var id = this.value[this.value.length - 1];
      //  console.log(this.value,55555);
      var sel = this.activeName;
      const { data: res } = await getCateList_api({ id, sel });
      // console.log(res, 8888888);
      //给获取的数组中每一项添加一个属性
      res.data.forEach(item => {
        item.inputVisible = false;
        item.inputValue = "";
        //渲染attr_vals 里的tag标签, 字符串转数组
        // item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        item.attr_vals = item.attr_vals
          .split(",")
          .filter(item => item.length != 0);
      });

      //显示table 判断时 only 还是 many
      if (this.activeName == "many") {
        this.manyDate = res.data;
      } else {
        this.onlyDate = res.data;
      }
    },
    //tab栏切换方法----------------------------------------
    handleClick() {
      this.paramsFunc();
    },
    //表单和按钮切换显示--------------------
    showInput(row) {
      row.inputVisible = !row.inputVisible;
      //button转input自动聚焦
      //$nextTick 当页面上的dom元素重新渲染时，触发回调函数
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 表单和按钮的切换添加属性---完成标签添加功能----------
    handleInputConfirm(row) {
      row.inputVisible = !row.inputVisible;
      // console.log(row,66666);
      if (row.inputValue.trim().length == 0) {
        row.inputValue = "";
        return;
      }
      //往attr_vals数组里面添加
      row.attr_vals.push(row.inputValue);
      // 重置为空
      row.inputValue = "";
      //关闭input
      row.inputVisible = false;
      //发送axios请求，保存到服务器
      /*  var params = {
        id: row.cat_id,
        attrId:row.attr_id,
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals:row.attr_vals.join(',')
      };
      const {data:res}=await putCategories_api(params); */
      // console.log(res,88888);
      this.addPut(row);
    },
    //添加属性函数封装------
    async addPut(row) {
      var params = {
        id: row.cat_id,
        attrId: row.attr_id,
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(",")
      };
      const { data: res } = await putCategories_api(params);
    },
    //表格删除功能----------------------------
    async handerDelete(row) {
      const res = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(() => {
        // .then 成功回调，打印 res=>{}  得到"confirm"
        this.$message({
          type: "info",
          message: "已取消删除"
        });
        return;
      });
      // console.log(row, 7777777);
      if (res == "confirm") {
        const { data: res } = await deleteCate_api({
          id: row.cat_id,
          attrid: row.attr_id
        });
        // console.log(res,111111);
        this.$message.success("删除成功");
        this.paramsFunc();
      }
    },
    //表格编辑功能------------------------------
    handerEdit(row) {
      this.dialogFormVisible = true;
      // console.log(row, 7777777);
      this.paramsForm = row;
    },
    //点击弹窗里的确认按钮-------------------
    editParams() {
      //做二次校验
      this.$refs.paramsFormDialog.validate(async valid => {
        if (valid) {
          const { data: res } = await editCategories_api(this.paramsForm);
          // console.log(res, 99999);
          this.$message.success("更新成功");
          this.dialogFormVisible = false;
        } else {
          this.$message.error("更新失败");
          return false;
        }
      });
    },
    //添加动态属性和静态属性---------------------------
    async addParams() {
      this.addDialogFormVisible = true;
    },
    //点击确认完成添加
    addParamsBtn() {
      this.$refs.paramsFormDialog.validate(async valid => {
        if (valid) {
          var id = this.cateId;
          var params = {
            id: id,
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          };
          const { data: res } = await addParams_api(params);
          // console.log(this.value[2], 222222);
          // console.log(res, 3333333);
          //更新表格
          this.paramsFunc();
          this.addDialogFormVisible = false;
        } else {
          this.$message.error("添加失败！");
          return false;
        }
        //清空表单-------------
        this.addForm = {};
        this.$refs.paramsFormDialog.resetFields();
      });
    },
    // //删除标签功能------就是从attr_vals数组里删除数据------------------
    delTag(i, row) {
      console.log(i, row, 888999);
      //  根据索引删除第几项 并只删除一个
      row.attr_vals.splice(i, 1);

      //更新数据
      this.addPut(row);
    }
  },

  //计算属性-------------------------------------------
  computed: {
    //获取三级层的cate_id
    cateId() {
      if (this.value.length == 3) {
        return this.value[2];
      }
      return null;
    }
    //  使用计算属性获取按钮的禁用状态
    /*  disabled() {
      if (this.value.length == 3) {
        return false
      } else {
        return true
      }
    }, */
  }
};
</script>
<style scoped>
</style>